import { hashLink } from "~utils/hashLink";
import getShortcutByName from "./slash/api/getShortcutByName";
import {clearViewstateFromSlash, fetchViewstateFromSlash, removeViewstateFromSlash, storeViewstateToSlash } from "./slash/slashStore";

const store = async (url: string, viewstate: string) => {
  const regex = /([a-f0-9]{40})/; // e.g. "slash.jimmymo.site/archive/08a8e69e4791f752421266c2a687ac0570d2af35.html"
  const match = url.match(regex);
  if (match) {
    const name = match[0];
    await storeViewstateToSlash(name, viewstate);
  } else {
    const name = hashLink(location.href); // 如果不是slash托管的网页，那么检查是否已记录在slash中，如果是，那么备注也保存在slash中。
    console.log(`url hash: ${name}`);
    const data = await getShortcutByName(name);
    if (data && data.shortcut) {
      await storeViewstateToSlash(name, viewstate);
    } else {
      console.log("storeViewstateToWebStorage!");
      // await storeViewstateToWebStorage(url, viewstate);
    }
  }
}
const fetch = async (url: string) => {
  const regex = /([a-f0-9]{40})/; // e.g. "slash.jimmymo.site/archive/08a8e69e4791f752421266c2a687ac0570d2af35.html"
  const match = url.match(regex);
  if (match) {
    const name = match[0];
    return await fetchViewstateFromSlash(name);
  } else {
    const name = hashLink(location.href); // 如果不是slash托管的网页，那么检查是否已记录在slash中，如果是，那么备注也保存在slash中。
    console.log(`url hash: ${name}`);
    const data = await getShortcutByName(name);
    if (data && data.shortcut) {
      return await fetchViewstateFromSlash(name);
    } else {
      console.log("fetchViewstateFromWebStorage!");
      // return await fetchViewstateFromWebStorage(url);
    }
  }
}

const remove = async (url: string, highlightId: string) => {
  const regex = /([a-f0-9]{40})/; // e.g. "slash.jimmymo.site/archive/08a8e69e4791f752421266c2a687ac0570d2af35.html"
  const match = url.match(regex);
  if (match) {
    const name = match[0];
    await removeViewstateFromSlash(name, highlightId);
  } else {
    const name = hashLink(location.href); // 如果不是slash托管的网页，那么检查是否已记录在slash中，如果是，那么备注也保存在slash中。
    console.log(`url hash: ${name}`);
    const data = await getShortcutByName(name);
    if (data && data.shortcut) {
      await removeViewstateFromSlash(name, highlightId);
    } else {
      console.log("removeViewstateFromWebStorage!");
      // await removeViewstateFromWebStorage(url, highlightId);
    }
  }
}

const clear = async (url: string) => {
  const regex = /([a-f0-9]{40})/; // e.g. "slash.jimmymo.site/archive/08a8e69e4791f752421266c2a687ac0570d2af35.html"
  const match = url.match(regex);
  if (match) {
    const name = match[0];
    await clearViewstateFromSlash(name);
  } else {
    console.log("clearViewstateFromWebStorage!");
    // await clearViewstateFromWebStorage(url);
  }
}

export {
  store,
  fetch,
  remove,
  clear,
}
